//
//  StatusPictureView.swift
//  JJWeibo
//
//  Created by JJ on 15/9/7.
//  Copyright © 2015年 JJ. All rights reserved.
//

import UIKit
import SDWebImage

private let JJStatusPictureViewCellID="JJStatusPictureViewCellID"

let JJStatusPictureViewSelectedPhotoNotification = "JJStatusPictureViewSelectedPhotoNotification"

let JJStatusPictureViewSelectedPhotoIndexPathKey = "JJStatusPictureViewSelectedPhotoIndexPathKey"

let JJStatusPictureViewSelectedPhotoURLsKey = "JJStatusPictureViewSelectedPhotoURLsKey"

class StatusPictureView: UICollectionView {
    
    
     var statusViewModel:StatusViewModel?{
        didSet{
            
            sizeToFit()
            reloadData()
        }
        
    }
    
    override func sizeThatFits(size: CGSize) -> CGSize {
       return calcViewSize()
    }

    
    private func calcViewSize()->CGSize{
        
        let layout=collectionViewLayout as! UICollectionViewFlowLayout
        layout.itemSize=CGSize(width: JJStatusPictureItemWidth, height: JJStatusPictureItemWidth)
        let count=statusViewModel?.thumbnailURLs?.count ?? 0
        if count==0{
            return CGSizeZero
        }
        
        if count==1{
            let key = statusViewModel!.thumbnailURLs![0].absoluteString
            let image=SDWebImageManager.sharedManager().imageCache.imageFromDiskCacheForKey(key)
            var size=image.size
            size.width=size.width < 40 ? 40 : size.width
            size.width=size.width > 300 ? 300:size.width
            layout.itemSize=size
            return size
        }
        
        if count==4{
            let w=2 * JJStatusPictureItemWidth + JJStatusPictureItemMargin
            return CGSize(width: w, height: w)
        }
        let row=CGFloat((count-1) / Int(JJStatusPictureMaxCount)+1)
        let h=row * JJStatusPictureItemWidth + (row-1) * JJStatusPictureItemMargin
        
        return CGSize(width: JJStatusPictureMaxWidth, height: h)
    }
    
    override init(frame: CGRect, collectionViewLayout layout: UICollectionViewLayout) {
        super.init(frame: frame, collectionViewLayout: UICollectionViewFlowLayout())
        backgroundColor=UIColor.lightGrayColor()
        
        let layout=collectionViewLayout as!UICollectionViewFlowLayout
        layout.minimumInteritemSpacing=JJStatusPictureItemMargin
        layout.minimumLineSpacing=JJStatusPictureItemMargin
        
        dataSource = self
        delegate=self
        
        registerClass(StatusPictureViewCell.self, forCellWithReuseIdentifier: JJStatusPictureViewCellID)
        
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

}

extension StatusPictureView:UICollectionViewDataSource,UICollectionViewDelegate{
    
    func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
        
//        let v=UIView(frame: fullScreenRect(indexPath))
//        
//        v.backgroundColor=UIColor.redColor()
//        UIApplication.sharedApplication().keyWindow?.addSubview(v)
        
        
        NSNotificationCenter.defaultCenter().postNotificationName(JJStatusPictureViewSelectedPhotoNotification, object: self, userInfo: [JJStatusPictureViewSelectedPhotoIndexPathKey:indexPath,
            JJStatusPictureViewSelectedPhotoURLsKey: statusViewModel!.bmiddleUrls!])
        
    }
     func screenRect(indexPath:NSIndexPath)->CGRect{
        
        let cell=cellForItemAtIndexPath(indexPath)
        
        return convertRect(cell!.frame, toCoordinateSpace: UIApplication.sharedApplication().keyWindow!)
    }
    
    func fullScreenRect(indexPath:NSIndexPath)->CGRect{
        
        let key=statusViewModel?.thumbnailURLs![indexPath.item].absoluteString
        let image=SDWebImageManager.sharedManager().imageCache.imageFromDiskCacheForKey(key)
        let scale=image.size.height / image.size.width
        let w=UIScreen.mainScreen().bounds.size.width
        let h = w * scale
        
        var y=(UIScreen.mainScreen().bounds.height - h) * 0.5
        if y < 0 {
           y=0
        }
        return CGRect(x: 0, y: y, width: w, height: h)
    }
    
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return statusViewModel?.thumbnailURLs?.count ?? 0
    }
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell=collectionView.dequeueReusableCellWithReuseIdentifier(JJStatusPictureViewCellID, forIndexPath: indexPath) as!StatusPictureViewCell
        
        cell.imageUrl=statusViewModel!.thumbnailURLs![indexPath.item]
        return cell
    }
}

private class StatusPictureViewCell: UICollectionViewCell {
    
    var imageUrl:NSURL?{
        didSet{
            iconView.sd_setImageWithURL(imageUrl)
            
        gifView.hidden = (imageUrl!.absoluteString as NSString).pathExtension.lowercaseString != "gif"
        }
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        addSubview(iconView)
        iconView.ff_Fill(self)
        
        iconView.addSubview(gifView)
        gifView.ff_AlignInner(type: ff_AlignType.BottomRight, referView: iconView, size: nil)
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    private lazy var iconView:UIImageView = {
        
        let iv=UIImageView()
        iv.contentMode=UIViewContentMode.ScaleAspectFill
        iv.clipsToBounds=true
        return iv
    }()
    private lazy var gifView:UIImageView=UIImageView(image: UIImage(named: "timeline_image_gif"))
}











